package com.example.aopproxy.component;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
public class ProxyFactory implements MethodInterceptor {

    @Autowired
    private Student student;

    public Student getProxyObject() {
        //1.创建 Enhancer 对象，类似于 JDK 动态代理 Proxy 类
        Enhancer enhancer = new Enhancer();
        //2.设置父类(代理类的父类就是被代理类)的字节码对象
        enhancer.setSuperclass(student.getClass());
        //3.设置回调函数
        enhancer.setCallback(this);
        //4.创建代理对象
        Student obj = (Student) enhancer.create();
        return obj;
    }


    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        method.invoke(student, objects);
        return null;
    }
}
